package com.kaikeba.estack.common.jdbc;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.kaikeba.estack.common.util.BeanUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 实现mysql数据库字段与javaBean之间的字段映射
 * bean：
 * id,name,inTime
 * db：
 * id,name,in_time
 *
 * @Auth xingwan
 * @Date 2020/9/6 23:29
 **/
public class BeanRowMapper<T> implements RowMapper<T> {

    private MapRowMapper mapRowMapper = MapRowMapper.getInstance();

    /**
     * 缓存class对应的mapper
     */
    private static final Map<Class<?>, BeanRowMapper<?>> FACTORY = new ConcurrentHashMap<>();

    private Class<T> tClass;

    public BeanRowMapper(Class<T> tClass) {
        this.tClass = tClass;
    }

    @Override
    public T mapRow(ResultSet resultSet, long rowNum) throws SQLException {
        Map<String, Object> row = mapRowMapper.mapRow(resultSet, rowNum);
        return BeanUtil.convert(row, tClass);
    }

    public static <T> BeanRowMapper<T> getInstance(Class<T> tClass) {
        return (BeanRowMapper<T>) FACTORY.computeIfAbsent(tClass, BeanRowMapper::new);
    }

}
